package com.ui;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;

import com.toedter.calendar.JDateChooser;
import com.util.Constantes;

import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Vector;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import com.controlador.Conexion;
import com.controlador.JavaExcelWriter;
import com.controlador.JavaPDFWriter;
import com.controlador.Operaciones;

import javax.swing.ImageIcon;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;





public class ReportePersonalizado extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private JDateChooser calendarioDesde;
	private JDateChooser calendarioHasta;
	private JTable tablaDatos;
	private String fInicio = new String();
	private String fFinal= new String();
	Object[][] dataObj = null;
	DefaultTableModel modelo = null;
	
	
	Conexion connex = new Conexion();
	Connection conn = null;
	Operaciones op = new Operaciones();
	

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ReportePersonalizado frame = new ReportePersonalizado();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ReportePersonalizado() {
		setTitle("Personalized Report");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 700, 450);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		calendarioDesde = new JDateChooser();
		
		JButton btnGenerar = new JButton("Generate");
		btnGenerar.addActionListener(new ActionListener() {
			//@SuppressWarnings("deprecation")
			public void actionPerformed(ActionEvent arg0) {
								
				if(calendarioDesde.getDate().after(calendarioHasta.getDate()))
				{
					JOptionPane.showMessageDialog(null,"End Date cannot be less than Start Date","Error",JOptionPane.ERROR_MESSAGE);
				}else{
					
					conn=connex.AccederBD();
					fInicio = new SimpleDateFormat("yyyy-MM-dd").format(calendarioDesde.getDate());
					fFinal = new SimpleDateFormat("yyyy-MM-dd").format(calendarioHasta.getDate());
				
					String ff = "fecha BETWEEN '"+fInicio+"' AND '"+fFinal+"'";
					
					DefaultTableModel m = (DefaultTableModel) tablaDatos.getModel();
					String[] encabezado = {"ID","Serial #","Model","Form Type","Process","Reuse","Engineer","User","Date"}; 
					Object[][] dataVector = op.select("Equipos", "id,noSerie,modelo,tipo,proceso,reuso,idIngeniero,usuario,fecha",ff, conn);
					m.setDataVector(dataVector, encabezado);
	
					
				}
				
			}
		});
		
		JLabel lblDesde = new JLabel("From:");
		
		JLabel lblHasta = new JLabel("To:");
		
		calendarioHasta = new JDateChooser();
		
		JScrollPane scrollPane = new JScrollPane();
		
		JButton button = new JButton("");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String[] encabezado = {"ID","Serial #","Model","Form Type","Process","Reuse","Engineer","User","Date"}; 
				Vector<?> m = modelo.getDataVector();
				new JavaPDFWriter().escribePDF(encabezado,m);
				//mandar abrir el archivo
				try 
				{ 
					String rutaAbsoluta = new File(Constantes.ARCHIVO_PDF_TEMPORAL).getAbsolutePath();
					@SuppressWarnings("unused")
					Process p = Runtime.getRuntime().exec ("rundll32 SHELL32.DLL,ShellExec_RunDLL "+ rutaAbsoluta ); 
					
				} 
				catch (Exception e) 
				{ 
					System.err.println("Error: "+e.getMessage()); 
				}
				
				
				
			}
		});
		button.setIcon(new ImageIcon(ReportePersonalizado.class.getResource("/com/util/img/pdf-ico.png")));
		
		JButton button_1 = new JButton("");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				DefaultTableModel m = (DefaultTableModel) tablaDatos.getModel();
				Vector<?> objTemp = m.getDataVector();
				String[] encabezado = {"ID","Serial #","Model","Form Type","Process","Reuse","Engineer","User","Date"};
				new JavaExcelWriter().escribeExcel(objTemp,encabezado);
				
				//mandar abrir el archivo
				try 
				{ 
					String rutaAbsoluta = new File(Constantes.ARCHIVO_EXCEL_TEMPORAL).getAbsolutePath();
					@SuppressWarnings("unused")
					Process p = Runtime.getRuntime().exec ("rundll32 SHELL32.DLL,ShellExec_RunDLL "+ rutaAbsoluta ); 
					
				} 
				catch (Exception e) 
				{ 
					System.err.println("Error: "+e.getMessage()); 
				}
				
				
			}
		});
		button_1.setIcon(new ImageIcon(ReportePersonalizado.class.getResource("/com/util/img/excel-ico.png")));
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addContainerGap(593, Short.MAX_VALUE)
					.addComponent(btnGenerar)
					.addContainerGap())
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGap(1)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 673, Short.MAX_VALUE)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(lblDesde)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(calendarioDesde, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(lblHasta)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(calendarioHasta, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED, 217, Short.MAX_VALUE)
							.addComponent(button)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(button_1))))
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addComponent(calendarioHasta, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(calendarioDesde, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
							.addComponent(lblDesde)
							.addComponent(lblHasta, Alignment.TRAILING))
						.addComponent(button_1)
						.addComponent(button))
					.addGap(12)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 283, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(btnGenerar)
					.addContainerGap())
		);
		
		
		 
		
		 //= op.select("Equipos", "id,noSerie,tipo,proceso,idIngeniero,usuario,fecha", fr,"proceso", conn);
		String[] encabezado = {"ID","Serial #","Model","Form Type","Process","Reuse","Engineer","User","Date"}; 
		modelo = new DefaultTableModel(dataObj,encabezado);
		tablaDatos = new JTable();
		tablaDatos.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				//detectar el numero de clicks
				//if(arg0.getClickCount()==2){
					//System.err.println(tablaDatos.get);
					int fil= tablaDatos.getSelectedRow();
					//int colum=tablaDatos.getSelectedColumn(); //se obtiene la columna
					String resul = (String) tablaDatos.getValueAt(fil, 0);//se pone en 0 por que no nos importa que selecione, solo la linea
					System.out.println(resul);
					//System.out.println(op.matrisALinea(op.select("Equipos", "noserie,tipo,proceso,reuso,status,idingeniero,usuario", "id="+resul, conn)));
					new RegistroEditar().populateInformacion(op.matrisALinea(op.select("Equipos", "id,noserie,tipo,proceso,reuso,status,idingeniero,usuario,modelo", "id="+resul, conn)));
				//}
			}
		});
		tablaDatos.setModel(modelo);
		
		scrollPane.setViewportView(tablaDatos);
		contentPane.setLayout(gl_contentPane);
		
	
		
	}
}
